<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <vxe-button size="medium" status="primary" icon="vxe-icon-square-plus" @click="insertEvent()">添加练车单</vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-table border class="mytable-scrollbar" show-footer stripe ref="xTable" height="400"
      :column-config="{ resizable: true }" :row-config="{ isHover: true }" :data="tableData">
      <vxe-column type="seq" title="序号" width="80" fixed="left"></vxe-column>
      <vxe-column field="stuname" title="训练学员" width="80" fixed="left"></vxe-column>
      <vxe-column field="license" title="训练车辆" width="150"></vxe-column>
      <vxe-column field="schoolName" title="校区" width="150"></vxe-column>
      <vxe-column field="object" title="科目" width="150"></vxe-column>
      <vxe-column field="coachname" title="教练姓名" width="150"></vxe-column>
      <vxe-column field="ordertime" title="预约时间" width="150"></vxe-column>
      <vxe-column field="startTime" title="开始时间" width="150"></vxe-column>
      <vxe-column field="endTime" title="结束时间" width="150"></vxe-column>
      <vxe-column field="tratime" title="练车时长" width="150"></vxe-column>
      <vxe-column field="upvotes" title="累计时长" width="150"></vxe-column>
      <vxe-column field="comment" title="备注" width="150"></vxe-column>
      <vxe-column title="操作" width="220" fixed="right" show-overflow>
        <template #default="{ row }">
          <vxe-button type="text" status="info" :disabled="row.upvotes < 19" @click="handleOrder"
            :style="row.upvotes < 19 ? '' : 'color:white;background:#7CFC00'" class="orderbutton"
            icon="vxe-icon-warnion-circle-fill">约考</vxe-button>
          <vxe-button type="text" class="printbutton" icon="vxe-icon-print" @click="editEvent(row)">打印</vxe-button>
          <vxe-button type="text" class="delbutton" icon="vxe-icon-delete" @click="removeEvent(row)">作废</vxe-button>
          <!-- <vxe-button type="text" icon="vxe-icon-delete" @click="removeEvent(row)"></vxe-button> -->
        </template>
      </vxe-column>
      <!-- <vxe-column field="sex" title="Sex" :formatter="formatterSex"></vxe-column> -->
    </vxe-table>

    <vxe-modal v-model="showEdit" :title="selectRow ? '编辑&保存' : '新增&保存'" width="800" min-width="600" min-height="300"
      resize destroy-on-close>
      <template #default>
        <vxe-form :data="formData" :rules="formRules" title-align="right" title-width="100" @submit="submitEvent">
          <vxe-form-item field="stuname" title="训练学员" :span="24" :item-render="{}">
            <template #default="{ data }">
              <vxe-select v-model="data.stuId" transfer placeholder="选择学员" @change="handleSelect">
                <vxe-option v-for="item in stunameList" :key="item.objectId" :value="item.objectId"
                  :label="item.name"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item field="schoolName" title="练车校区" :span="24" :item-render="{}">
            <template #default="{ data }">
              <vxe-select v-model="data.schoolName" transfer placeholder="选择校区">
                <vxe-option v-for="item in schoolList" :key="item.objectId" :value="item.schoolName"
                  :label="item.schoolName"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item field="object" title="练车科目" :span="24" :item-render="{}">
            <template #default="{ data }">
              <vxe-select v-model="data.object" transfer placeholder="选择科目" @change="handleChange">
                <vxe-option v-for="item in objectList" :key="item.value" :value="item.value"
                  :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item field="coachname" title="培训教练" :span="24" :item-render="{}">
            <template #default="{ data }">
              <vxe-select v-model="data.coachname" transfer placeholder="选择教练">
                <vxe-option v-for="item in coachList" :key="item.objectId" :value="item.name"
                  :label="item.name"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item field="license" title="使用车辆" :span="24" :item-render="{}">
            <template #default="{ data }">
              <vxe-select v-model="data.license" transfer placeholder="选择使用的车辆">
                <vxe-option v-for="item in licenseList" :key="item.objectId" :value="item.license"
                  :label="item.license"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item field="ordertime" title="预约时间" :span="12" :item-render="{}">
            <template #default="{ data }">
              <vxe-input v-model="data.ordertime" type="date" placeholder="请选择预约时间" transfer></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item field="tratime" title="练车时长" :span="12" :item-render="{}">
            <template #default="{ data }">
              <vxe-input v-model="data.tratime" placeholder="请输入名称"></vxe-input>
            </template>
          </vxe-form-item>

          <vxe-form-item field="timerange" title="练车时段" :span="24" :item-render="{}">
            <div class="demo-time-range">
              <el-row>
                <el-col :span="12">
                  <el-time-select v-model="startTime" :span="12" :max-time="endTime" class="mr-4" placeholder="开始时间"
                    start="08:30" step="00:15" end="18:30" />
                </el-col>
                <el-col :span="12">
                  <el-time-select v-model="endTime" :span="12" :min-time="startTime" placeholder="结束时间" start="08:30"
                    step="00:15" end="18:30" />
                </el-col>
              </el-row>
            </div>
          </vxe-form-item>
          <vxe-form-item field="comment" title="练车备注" :span="24" :item-render="{}" :title-suffix="{
            message: '有事及时备注',
            icon: 'vxe-icon-question-circle-fill',
          }">
            <template #default="{ data }">
              <vxe-textarea v-model="data.comment" :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入练车备注内容"></vxe-textarea>
            </template>
          </vxe-form-item>
          <vxe-form-item align="center" title-align="left" :span="24">
            <template #default>
              <vxe-button type="submit">提交</vxe-button>
              <vxe-button type="reset">重置</vxe-button>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
    </vxe-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { VxeFormPropTypes, VXETable, VxeTableInstance } from "vxe-table";
import {
  studentGet,
  coachGet,
  carGet,
  tranrecorddPost,
  tranrecorddGet,
  tranRecorddDelete,
  totalInc,
} from "../../../api/trarecord";
import { StudentType, CarType, coachType } from "../../../types/trarecord";
import { schoolGet } from "../../../api/coachmange";
interface RowVO {
  stuname: string;
  schoolName: string;
  object: string;
  coachname: string;
  license: string;
  ordertime: string;
  tratime: number;
  upvotes: number;
  startTime: string;
  endTime: string;
  comment: string;
  objectId: string;
  total: number;
}
// elem时间组件
const startTime = ref("");
const endTime = ref("");
const formData = reactive({
  stuname: "",
  schoolName: "",
  object: "",
  coachname: "",
  license: "",
  ordertime: "",
  tratime: 0,
  startTime: "",
  endTime: "",
  comment: "",
  stuId: "",
  Dirsingle: "",
});

const showEdit = ref(false);
const selectRow = ref<RowVO | null>();
const xTable = ref<VxeTableInstance<RowVO>>();
const tableData = ref<RowVO[]>([]);

// 表格相关
const editEvent = (row: RowVO) => {
  Object.assign(formData, row);
  selectRow.value = row;
  showEdit.value = true;
};

// 表单相关
const schoolList = ref<any>([]);
schoolGet().then((res) => {
  schoolList.value = res.data.results;
});

const objectList = ref([
  { label: "科目二", value: "科目二" },
  { label: "科目三", value: "科目三" },
]);
const stunameList = ref<StudentType[]>([
  // { label: '小明', value: '小明' },
]);
const coachList = ref<coachType[]>([]);
const licenseList = ref<CarType[]>([]);

const formRules = reactive<VxeFormPropTypes.Rules>({
  stuname: [{ required: true, message: "选择学员" }],
  object: [{ required: true, message: "请选择科目" }],
  coachname: [{ required: true }],
  tratime: [{ required: true }],
});
// 删除练车单
const removeEvent = async (row: RowVO) => {
  const type = await VXETable.modal.confirm("您确定要删除该数据?");
  if (type === "confirm") {
    const $table = xTable.value;
    tranRecorddDelete(row.objectId).then(() => {
      // console.log("删除了", row.objectId);
      VXETable.modal.message({ content: "删除成功", status: "success" });
    });
    if ($table) {
      $table.remove(row);
    }
  }
};
const insertEvent = () => {
  // 点进去全部清空
  Object.assign(formData, {
    stuname: "",
    schoolName: "",
    object: "",
    coachname: "",
    license: "",
    ordertime: "",
    tratime: "",
    startTime: "",
    endTime: "",
    comment: "",
  });
  selectRow.value = null;
  showEdit.value = true;
};

const handleChange = (value: any) => {
  coachGet(value.value).then((res) => {
    coachList.value = res.data.results;
  });
};
const handleSelect = (value: any) => {
  stunameList.value.forEach((item: StudentType) => {
    if (item.objectId == value.value) {
      formData.stuname = item.name;
    }
  });
};

const handleOrder = () => {
  window.open("https://gab.122.gov.cn/m/login");
};

// 新增练车单
// 生成练车单号
const now = new Date();
let str = now
  .toLocaleString()
  .split("/")
  .join("")
  .split(":")
  .join("")
  .split(" ")
  .join("");

const submitEvent = (data: any) => {
  formData.startTime = startTime.value;
  formData.endTime = endTime.value;
  formData.Dirsingle = str;
  data.data.tratime = Number(data.data.tratime);
  showEdit.value = false;
  tranrecorddPost(data.data).then((res) => {
    let tratime = data.data.tratime;
    let { objectId } = res.data;

    // 累计时长
    totalInc(objectId, tratime).then(() => { });
    const $table = xTable.value;
    if ($table) {
      // showEdit.value = false
      if (selectRow.value) {
        VXETable.modal.message({ content: "保存成功", status: "success" });
        Object.assign(selectRow.value, formData);
      } else {
        VXETable.modal.message({ content: "新增成功", status: "success" });
        $table.insert({ ...formData });
      }
    }
  });
};
// 表格模板
tranrecorddGet().then((res) => {
  const list: RowVO[] = res.data.results;
  tableData.value = list;
});

studentGet().then((res) => {
  stunameList.value = res.data.results;
});

carGet().then((res) => {
  licenseList.value = res.data.results;
});
</script>
<style scoped lang="scss">
.delbutton {
  background: #ff5722;
  color: white;
}

.printbutton {
  background: #ffb800;
  color: white;
  margin-left: 5px;
  margin-right: 5px;
}

.orderbutton {
  background: #1e9fff;
  color: white;
}

.textsize {
  font-size: 30px;
}
</style>